/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* reverseBetween(ListNode* head, int m, int n){
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* pre = dummy, *cur = head;
        for(int i = 1; i < m; ++i){
            pre= cur;
            cur = cur->next;
        }
        for(int i = m; i < n; ++i){
            ListNode* tmp = cur->next;
            cur->next = tmp->next;
            tmp->next = pre->next;
            pre->next = tmp;
        }
        return dummy->next;
    }

    ListNode* reverseKGroup(ListNode* head, int k) {
        if(head == NULL || k <= 1) return head;
        ListNode* cur = head;
        int len = 0;
        while(cur){
            len += 1;
            cur = cur->next;
        }
        for(int m = 1, n = k; n <= len; m += k, n += k){
            head = reverseBetween(head, m, n);
        }
        return head;
    }
};